package com.charlie.mail;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.PatternSyntaxException;

/**
 *
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
public class MailTemplate {

    private String data;
    
    public MailTemplate(MailTemplateType tpl) {
        String root = (String) System.getProperties().get("com.sun.aas.instanceRoot");
        load(root + "/docroot/" + tpl.getFilename());
    }
   
    private void load(String filename) {
        File file = new File(filename);
        FileReader reader = null;
        data = "";
        try {
            reader = new FileReader(file);
            char[] chars = new char[(int) file.length()];
            reader.read(chars);
            data = new String(chars);
        } catch (IOException ex) {
            Logger.getLogger(MailTemplate.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(MailTemplate.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public void setParametr(String name, String value) {
        try {
            data = data.replaceAll("(<%" + name + "%>)", value);
        } catch (PatternSyntaxException ex) {
            Logger.getLogger(MailTemplate.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public String getData() {
        return data;
    }
}
